<template>
  <div :class="['carbill', { 'carbill-select': isSelect }]" v-loading="pageLoading">
    <el-tabs
      class="carbill-status"
      v-model="currentCarbillStatus"
      @tab-change="changeCarbillStatus"
    >
      <el-tab-pane v-for="item in carbillStatus" :key="item.name" v-bind="item"></el-tab-pane>
    </el-tabs>
    <div class="carbill-operate"></div>
    <div class="carbill-table-container">
      <el-table class="carbill-table" :data="tableData" @select="selectRow">
        <hs-table-column
          v-for="item in columns"
          :prop="item.prop"
          :key="item.prop"
          :label="item.title"
          v-bind="item"
        />
      </el-table>
    </div>
    <div class="carbill-footer">
      <p style="margin-right: auto">
        共计 <span style="color: var(--el-color-primary)">{{ query.total }}</span> 条
      </p>
      <el-pagination
        v-model:current-page="query.pageNum"
        :page-size="query.pageSize"
        :page-sizes="[20, 50, 100]"
        layout="prev, pager, next, sizes"
        :total="query.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup>
import api from '@/http/index'
import HsTableColumn from '@/components/Table/TableColumn.vue'
import { Carbill_Status_Enum } from '@/common/enum'
import { wait } from '@/common/utils/queue'
import { onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import useLayoutStore from '@/stores/layout'
const route = useRoute()
const layoutStore = useLayoutStore()
// 用于支持跳转选择出车单
const isSelect = !!route.query.isSelect
const localCacheKey = route.query.localCacheKey

if (isSelect) {
  layoutStore.hideAside = true
  layoutStore.pageTitle = '选择出车单'
}

const pageLoading = ref(false)
const columns = [
  {
    type: 'selection',
    fixed: 'left',
  },
  {
    prop: 'carbillId',
    title: '出车单号',
    width: 200,
  },
  {
    prop: 'driverName',
    title: '驾驶员',
    width: 120,
  },
  {
    prop: 'driverLicense',
    title: '驾驶车辆',
    width: 120,
  },
  {
    prop: 'phoneNumber',
    title: '联系电话',
    width: 140,
  },
  {
    prop: 'departDate',
    title: '发车时间',
  },
  {
    prop: 'arriveDate',
    title: '到达时间',
  },
  {
    prop: 'location',
    title: '车辆位置',
    fieldType: 'map',
  },
  {
    prop: 'carbillStatus',
    title: '出车单状态',
    fieldType: 'tag',
  },
]
const carbillStatus = [
  {
    label: '全部',
    name: 'all',
  },
  ...Object.keys(Carbill_Status_Enum).map((key) => ({
    label: Carbill_Status_Enum[key].text,
    name: key,
  })),
]
const currentCarbillStatus = ref('all')
const changeCarbillStatus = (status) => {
  currentCarbillStatus.value = status
  if (status === 'all') {
    delete query.carbillStatus
  } else {
    query.carbillStatus = status
  }
  query.pageNum = 1
  decodeLocation.cancel()
  getTableData()
}

const tableData = ref([])

const query = reactive({
  pageNum: 1,
  pageSize: 20,
  totalPage: null,
  total: null,
})
const handleSizeChange = (v) => {
  query.pageSize = v
  query.pageNum = 1
  decodeLocation.cancel()
  getTableData()
}
const handleCurrentChange = (v) => {
  query.pageNum = v
  decodeLocation.cancel()
  getTableData()
}

const getTableData = () => {
  pageLoading.value = true
  api.carbill
    .list(query)
    .then((result) => {
      tableData.value = (result.data?.list || []).map((item) => ({
        ...item,
        carbillStatus: Carbill_Status_Enum[item.carbillStatus],
        driverName: item?.driver?.user?.nickName,
        driverLicense: item?.driver?.driverLicense,
        phoneNumber: item?.driver?.user?.phonenumber,
        location:
          item.carLon && item.carLat && item.carbillStatus === 'transiting'
            ? loadLocation(item.carLon, item.carLat)
            : '',
      }))
      query.totalPage = result?.data?.totalPage
      query.total = result?.data?.total
    })
    .finally(() => {
      pageLoading.value = false
    })
}

const decodeLocation = wait(api.map.decode, 1000)

const loadLocation = (lon, lat) => {
  return decodeLocation({ lon, lat }).then((result) => {
    return result?.data?.formatted_address_poi
  })
}

getTableData()

const selectRow = (selection, row) => {
  if (isSelect) {
    const cacheData = JSON.parse(localStorage.getItem(localCacheKey))
    cacheData.carbillId = row.carbillId
    localStorage.setItem(localCacheKey, JSON.stringify(cacheData))
    const returnUrl = decodeURIComponent(route.query.returnUrl)
    window.location.href = returnUrl
  }
}

onUnmounted(() => {
  decodeLocation.cancel()
})
</script>

<style lang="scss">
.carbill {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  &-select {
    .el-table__header {
      thead {
        .el-table-column--selection {
          .el-checkbox {
            display: none;
          }
        }
      }
    }
  }
  &-status {
    .el-tabs__header {
      margin: 0;
    }
    .el-tabs__nav-scroll {
      padding: 0 20px;
    }
    .el-tabs__item {
      height: 47px;
    }
  }
  &-table-container {
    flex: 1;
    padding: 20px;
    overflow: hidden;
  }
  &-table {
    height: 100%;
    overflow-y: auto;
    thead {
      color: #262626;
      th {
        font-weight: 500;
      }
    }
  }
  &-footer {
    display: flex;
    align-items: center;
    padding: 20px;
    padding-top: 0;
  }
}
</style>
